package com.xiangb.springbootjpa.service.impl;

import com.xiangb.springbootjpa.common.PageVO;
import com.xiangb.springbootjpa.dao.PersonRepository;
import com.xiangb.springbootjpa.entity.Person;
import com.xiangb.springbootjpa.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2020/12/22 11:09
 */
@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person findById(Integer id) {
        Optional<Person> optionalPerson = personRepository.findById(id);
        if (optionalPerson != null && optionalPerson.isPresent()) {
            return optionalPerson.get();
        }
        return null;
    }

    /**
     * 事务管理测试
     * 两条数据同时成功，或者同时不成功
     * 保证数据库数据的完整性和一致性
     */
    @Transactional
    public void insertTwo(){
        Person personA = new Person();
        personA.setName("秋雅");
        personA.setAge(19);
        personRepository.save(personA);

        System.out.print("保存成功：id=" + personA.getId());

        Person personB = new Person();
        personB.setName("梦特娇");
        personB.setAge(25);
        personRepository.save(personB);
    }

    @Transactional
    public void save(String name, Integer age){
        Person person = personRepository.findByName(name);
        if (person == null) {
            person = new Person();
            person.setName(name);
            person.setAge(age);
        }else {
            person.setAge(age);
        }
        personRepository.save(person);
    }

    @Override
    public PageVO<Person> findByPage(int pageNumber, int pageSize, String likeName, Integer age) {
        PageVO<Person> pageVO = new PageVO<>();
        // pageable默认是从0开始的 page如果为null或者小于0,则page为0，否则-1
        pageNumber = pageNumber < 0? 0: pageNumber-1;
        //分页、排序信息
        Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.Direction.DESC, "id");
        Specification<Person> specification = new Specification<Person>() {
            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.hasLength(likeName)) {
                    list.add(criteriaBuilder.like(root.get("name"), "%" + likeName + "%"));
                }
                if (age != null) {
                    list.add(criteriaBuilder.equal(root.get("age"), age));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        };
        Page<Person> page = personRepository.findAll(specification, pageable);
        pageVO.pageToVO(page);
        return pageVO;
    }
}
